<?php

namespace cunzan\traits;

use Tools\Hyperf\Utils\WxCode;
use think\Exception;
use think\exception\HttpResponseException;
use think\facade\Db;
use think\facade\View;
use Think\Hook;
use Tools\Hyperf\Utils\Code;
use think\Model;
use think\Response;

trait ReturnContent
{
    public $code = [];

    protected function redirectJump(string $path)
    {
        if (request()->isAjax()) {
            throw new Exception("ajax 不支持重定向");
        }

        $host = request()->header("host");
        $login = "http://" . $host . DS . $path;
        return redirect($host);;
    }

    protected function wxAjaxPage(int $code, string $msg = '',array $list = [], int $hasmore=0, $url = '')
    {
        header('Content-Type:application/json; charset=utf-8');

        $return = [
            'code' => $code,
            'msg' => Code::$message[$code] ?? $msg,
            'hasmore'=> $hasmore,
            'list' => $list,
        ];
        if($url){
            $return['url'] = $url;
        }

        if ($url) $return['url'] = $url;
        $response = Response::create($return, 'json',200);
        throw new HttpResponseException($response);
    }

    /**
     * @param int $code
     * @param string $msg
     * @param array $data
     * @param string $url
     */
    protected function wxAjax(int $code, string $msg, $data = [], string $url='')
    {
        header('Content-Type:application/json; charset=utf-8');

        $return = [
            'code' => $code,
            'msg' => Code::$message[$code] ?? $msg,
            'data' => $data instanceof Model ? $data->toArray() : $data,
        ];
        if($url){
            $return['url'] = $url;
        }

        if ($url) $return['url'] = $url;
        $response = Response::create($return, 'json',200);
        throw new HttpResponseException($response);
    }

    protected function errorAjax(int $code = 0, string $msg = '', $data = '', $url = '')
    {
        $msg = Code::$message[$code] ?? $msg;
        return $this->returnAjax($code, $msg, $data, $url);
    }

    protected function successAjax(int $code = 20000, string $msg = '', $data = '', $url = '')
    {
        $msg = Code::$message[$code] ?? $msg;
        return $this->returnAjax($code, $msg, $data, $url);
    }

    private function returnAjax(int $code, string $msg = '', $data = '', $url = '')
    {
        header('Content-Type:application/json; charset=utf-8');

        $return = [
            'code' => $code,
            'msg' => Code::$message[$code] ?? $msg,
            'data' => $data
        ];

        if ($url) $return['url'] = $url;
        $response = Response::create($return, 'json',200);
        $response->send();
    }

    private function dispatchJump($message, $status = 1, $jumpUrl = '', $ajax = false)
    {
        if (true === $ajax || request()->isAjax()) {// AJAX提交
            $data = is_array($ajax) ? $ajax : array();
            $data['info'] = $message;
            $data['status'] = $status;
            $data['url'] = $jumpUrl;
            return ($data);
        }
        if (is_int($ajax)) View::assign('waitSecond', $ajax);
        if (!empty($jumpUrl)) View::assign('jumpUrl', $jumpUrl);
        // 提示标题
        View::assign('msgTitle', $status ? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_'));
        //如果设置了关闭窗口，则提示完毕后自动关闭窗口
        if (view()->get('closeWin')) View::assign('jumpUrl', 'javascript:window.close();');
        View::assign('status', $status);   // 状态
        //保证输出不受静态缓存影响
        config('view.HTML_CACHE_ON', false);
        if ($status) { //发送成功信息
            View::assign('message', $message);// 提示信息
            // 成功操作后默认停留1秒
            if (!isset($this->waitSecond)) View::assign('waitSecond', '1');
            // 默认操作成功自动返回操作前页面
            if (!isset($this->jumpUrl)) View::assign("jumpUrl", $_SERVER["HTTP_REFERER"]);
            view()->display(config('view.TMPL_ACTION_SUCCESS'));
        } else {
            View::assign('error', $message);// 提示信息
            //发生错误时候默认停留3秒
            if (!isset($this->waitSecond)) View::assign('waitSecond', '3');
            // 默认发生错误的话自动返回上页
            if (!isset($this->jumpUrl)) View::assign('jumpUrl', "javascript:history.back(-1);");
            view()->display(config('view.TMPL_ACTION_ERROR'));
            // 中止执行  避免出错后继续执行
            exit;
        }
    }

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param string $message 提示信息
     * @param string $jumpUrl 页面跳转地址
     * @param mixed $ajax 是否为Ajax方式 当数字时指定跳转时间
     * @return void
     */
    protected function successDisplay($message = '', $jumpUrl = '', $ajax = false)
    {
        $this->dispatchJump($message, 1, $jumpUrl, $ajax);
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param string $message 错误信息
     * @param string $jumpUrl 页面跳转地址
     * @param mixed $ajax 是否为Ajax方式 当数字时指定跳转时间
     * @return void
     */
    protected function errorDisplay($message = '', $jumpUrl = '', $ajax = false)
    {
        $this->dispatchJump($message, 0, $jumpUrl, $ajax);
    }

    public function errorRollback(int $code, string $msg, $data = '', $url = '')
    {
        Db::rollback();
        $this->errorAjax($code, $msg, $data, $url);
    }

    /**
     * Ajax方式返回数据到客户端
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type AJAX返回数据格式
     * @param int $json_option 传递给json_encode的option参数
     * @return void
     */
    protected function ajaxReturn($data, $type = '', $json_option = 0)
    {
        if (empty($type)) $type = config('DEFAULT_AJAX_RETURN');
        switch (strtoupper($type)) {
            case 'JSON' :
                ob_clean();
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode($data, $json_option));
            case 'XML'  :
                // 返回xml格式数据
                header('Content-Type:text/xml; charset=utf-8');
                exit(xml_encode($data));
            case 'JSONP':
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                $handler = isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
                exit($handler . '(' . json_encode($data, $json_option) . ');');
            case 'EVAL' :
                // 返回可执行的js脚本
                header('Content-Type:text/html; charset=utf-8');
                exit($data);
            default     :
                // 用于扩展其他返回格式数据
                Hook::listen('ajax_return', $data);
        }
        exit;
    }
}
